package org.sang.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.sang.bean.User;
import org.sang.common.UserUtils;
import org.sang.exception.MemberBaiscException;
import org.sang.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by sang on 2017/12/28.
 */
@Service
@Transactional
public class UserService implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userMapper.loadUserByUsername(s);
        if (user == null) {
            throw new UsernameNotFoundException("用户名不对");
        }
        return user;
    }

    public List<User> getUsersByKeywords(String keywords) {
        return userMapper.getUsersByKeywords(keywords);
    }

    public int updateUser(User user) {
        return userMapper.updateUser(user);
    }

    public int updateUserRoles(Long userId, Long[] rids) {
        int i = userMapper.deleteRoleByUserId(userId);
        return userMapper.addRolesForUser(userId, rids);
    }

    public User getUserById(Long userId) {
        return userMapper.getUserById(userId);
    }

    public int deleteUser(Long userId) {
        return userMapper.deleteUser(userId);
    }

    public List<User> getAllUserExceptAdmin() {
        return userMapper.getAllUser(UserUtils.getCurrentUser().getId());
    }

    public List<User> getAllUser() {
        return userMapper.getAllUser(null);
    }


    public int add(User user) {
        if (userMapper.loadUserByUsername(user.getUsername()) != null) {
            throw new MemberBaiscException("用户名重复，注册失败");
        }
        if (userMapper.getCountByworkNo(user.getWorkNo()) > 0) {
            throw new MemberBaiscException("工号重复，注册失败");
        }

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(user.getPassword());
        user.setPassword(encode);
        int result = userMapper.userReg(user);
        if (result > 0) {
            User u = userMapper.loadUserByUsername(user.getUsername());
            Long[] roles = user.getRoles().stream().map(item -> item.getId()).toArray(Long[]::new);
            userMapper.addRolesForUser(u.getId(), roles);
        }
        return 1;
    }

    public void delete(long id) {
        try {
            userMapper.deleteUser(id);
        } catch (Exception e) {
            e.printStackTrace();
            throw new MemberBaiscException("删除失败");
        }
    }

    public int update(User user, long id) {
        int result;
        try {
            user.setId(id);
            //不更新密码
            user.setPassword(null);
            result = userMapper.updateUser(user);
            if (result > 0) {
                Long[] roles = user.getRoles().stream().map(item -> item.getId()).toArray(Long[]::new);
                userMapper.deleteRoleByUserId(id);
                userMapper.addRolesForUser(user.getId(), roles);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new MemberBaiscException("修改失败");
        }
        return result;
    }

    public User findOne(long id) {
        return userMapper.getUserById(id);
    }

    public Page<User> getUserListByPage(int pageNum, int pageSize, User user) {
        Page<User> result = PageHelper.startPage(pageNum, pageSize);
        userMapper.getUsers(user);
        return result;

    }
}
